import React, { useState, useEffect } from 'react'
import { IconFont, axiosConfig, backIP, error, success } from '../common/config';
import styles from '../../styles/home/totalClassShow.scss'
import axios from 'axios'
import { Space, Table, Modal, Button, Input, InputNumber, Select } from 'antd';
import { getToken } from '../common/util';
const { Option } = Select;

interface identifyConfig {
    id: number
    value: string
}

interface userDetailConfig {
    number: string,
    real_name: string,
    password?: string
    college: identifyConfig,
    grade: string,
    class: string,
}

interface userItemConfig {
    key: number,
    number: string,
    real_name: string,
    identifyID: number
    identifyValue: string
    jurisdictionID: number
    jurisdictionValue: string
}

const jurisdictionContarst = {
    common: '普通用户',
    admin: '管理员'
}

interface UserListShowConfig {
    addIndex: number | null
    setAddIndex: React.Dispatch<React.SetStateAction<number>>
}

export default function UserListShow({ addIndex, setAddIndex }: UserListShowConfig) {
    const [userList, setUserList] = useState<userItemConfig[]>([])
    const [identifyList, setIdentifyList] = useState<identifyConfig[]>([])
    const [jurisdictionList, setJurisdictionList] = useState<identifyConfig[]>([])
    const [collegeList, setCollegeList] = useState<identifyConfig[]>([])
    const [visible, setVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    const [userDetail, setUserDetail] = useState<userDetailConfig | null>(null)
    const [editUserID, setEditUserID] = useState<number | null>(null)
    useEffect(() => {
        if (addIndex === 3) {
            setVisible(true)
            setUserDetail({
                number: '',
                real_name: '',
                college: {
                    id: 1,
                    value: '计算机学院'
                },
                grade: '2018',
                class: ''
            })
        }
    }, [addIndex])
    useEffect(() => {
        getUserList()
        getIdentifyList()
        getjurisdictionList()
        getCollegeList()
    }, [])
    const getUserList = async () => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/user/list`, {
            headers: {
                Authorization: token,
            }
        })
        let arr: userItemConfig[] = []
        if (res.code === 0) {
            arr = res.data.map(item => {
                return {
                    identifyID: item.identify.id,
                    identifyValue: item.identify.value,
                    jurisdictionID: item.jurisdiction.id,
                    jurisdictionValue: item.jurisdiction.value,
                    key: item.id,
                    number: item.number,
                    real_name: item.real_name
                }
            })
        } else {
            error(res.message)
        }
        setUserList(arr)
    }
    const getIdentifyList = async () => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/identify/list`, {
            headers: {
                Authorization: token,
            }
        })
        setIdentifyList(res.data)
    }
    const getjurisdictionList = async () => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/jurisdiction/list`, {
            headers: {
                Authorization: token,
            }
        })
        setJurisdictionList(res.data)
    }
    const getCollegeList = async () => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/college`, {
            headers: {
                Authorization: token,
            }
        })
        setCollegeList(res.data)
    }
    const handleIdentifyChange = async (value: number, userID: number) => {
        const token: string = getToken();
        await axios.post(`${backIP}/identify/modify`, {
            id: userID,
            identify_id: value
        }, {
            headers: {
                Authorization: token
            }
        })
    }
    const handleJuridictionChange = async (value: number, userID: number) => {
        const token: string = getToken();
        await axios.post(`${backIP}/jurisdiction/modify`, {
            id: userID,
            jurisdiction_id: value
        }, {
            headers: {
                Authorization: token
            }
        })
    }
    const getUserDetail = async (userID: number) => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/user/detail`, {
            params: {
                user_id: userID
            },
            headers: {
                Authorization: token,
            }
        })
        setUserDetail(res.data)
    }
    const handleOk = async () => {
        if (!(userDetail.number && userDetail.class && userDetail.grade && userDetail.real_name)) {
            error('参数不能为空')
            return
        }
        setLoading(true)
        const token: string = getToken();
        const type = addIndex === 3 ? 'add' : 'modify'
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/user/${type}`, {
            id: editUserID,
            number: userDetail.number,
            real_name: userDetail.real_name,
            password: userDetail.password,
            college_id: userDetail.college.id,
            grade: userDetail.grade,
            class: userDetail.class
        }, {
            headers: {
                Authorization: token
            }
        })
        res.code === 0 ? success(res.message) : error(res.message)
        getUserList()
        setVisible(false)
        setLoading(false)
        setAddIndex(null)
    }
    const handleChange = (value, key: string) => {
        const tempUserDetail = JSON.parse(JSON.stringify(userDetail));
        tempUserDetail[key] = value
        setUserDetail(tempUserDetail)
    }
    const handleCollegeChange = (id: number) => {
        const tempUserDetail = userDetail;
        let tempCollege: identifyConfig;
        collegeList.map(collegeItem => {
            if (collegeItem.id === id) {
                tempCollege = collegeItem
            }
        })
        tempUserDetail.college = tempCollege
        setUserDetail(tempUserDetail)
    }
    const deleteUser = async (userID: number) => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.post(`${backIP}/user/remove`, {
            id: userID,
        }, {
            headers: {
                Authorization: token
            }
        })
        res.code === 0 ? success(res.message) : error(res.message)
        getUserList()
    }
    const columns = [
        {
            title: '学号',
            dataIndex: 'number',
            width: 180,
        },
        {
            title: '姓名',
            dataIndex: 'real_name',
            width: 180,
        },
        {
            title: '身份',
            dataIndex: 'identifyValue',
            width: 180,
            render: (text, record: userItemConfig) => {
                return <Select defaultValue={text} style={{ width: 120 }} onChange={(value: number) => { handleIdentifyChange(value, record.key) }}>
                    {
                        identifyList.map(identifyItem => {
                            return <Option value={identifyItem.id}>{identifyItem.value}</Option>
                        })
                    }
                </Select>
            }
        },
        {
            title: '权限',
            dataIndex: 'jurisdictionValue',
            width: 180,
            render: (text, record: userItemConfig) => {
                return <Select
                    defaultValue={jurisdictionContarst[text]}
                    style={{ width: 120 }}
                    onChange={(value: number) => { handleJuridictionChange(value, record.key) }}
                >
                    {
                        jurisdictionList.map(jurisdictionItem => {
                            return <Option value={jurisdictionItem.id}>{jurisdictionContarst[jurisdictionItem.value]}</Option>
                        })
                    }
                </Select>
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: 180,
            render: (text, record: userItemConfig) => (
                <Space size="middle">
                    <IconFont
                        type='iconxiugai07'
                        className={styles.icon}
                        onClick={() => { setVisible(true); getUserDetail(record.key); setEditUserID(record.key) }}
                    />
                    <IconFont
                        type='iconshanchu'
                        className={styles.icon}
                        onClick={() => { deleteUser(record.key) }}
                    />
                </Space>
            ),
        },
    ];
    return (
        <>
            <Table columns={columns} dataSource={userList} />
            <Modal
                visible={visible}
                onOk={handleOk}
                footer={[
                    <Button key="back" onClick={() => { setVisible(false); setAddIndex(null) }}>
                        取消
                  </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                        {addIndex === 3 ? '增加' : '修改'}
                    </Button>,
                ]}
                onCancel={() => { setVisible(false); setAddIndex(null) }}
            >
                {
                    userDetail && <>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>学号：</div>
                            <Input placeholder="请输入学号" value={userDetail.number} onChange={(e) => { handleChange(e.target.value, 'number') }} />
                        </div>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>姓名：</div>
                            <Input placeholder="请输入姓名" value={userDetail.real_name} onChange={(e) => { handleChange(e.target.value, 'real_name') }} />
                        </div>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>密码：</div>
                            <Input placeholder="请输入密码" value={userDetail.password || ''} onChange={(e) => { handleChange(e.target.value, 'password') }} />
                        </div>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>学院：</div>
                            <Select
                                defaultValue={userDetail.college.value}
                                style={{ width: 120 }}
                                onChange={(value: any) => { handleCollegeChange(value) }}
                            >
                                {
                                    collegeList.map(collegeItem => {
                                        return <Option key={collegeItem.id} value={collegeItem.id}>{collegeItem.value}</Option>
                                    })
                                }
                            </Select>
                        </div>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>年级：</div>
                            <Input placeholder="请输入年级" value={userDetail.grade} onChange={(e) => { handleChange(e.target.value, 'grade') }} />
                        </div>
                        <div className={styles.inputLayout}>
                            <div style={{
                                width: 67
                            }}>班级：</div>
                            <Input placeholder="请输入班级" value={userDetail.class} onChange={(e) => { handleChange(e.target.value, 'class') }} />
                        </div>
                    </>
                }
            </Modal>
        </>
    )
}
